<?php
/**
 * 
 * 
 * @author mattevigo
 * 
 * @project Sandro del Pistoia
 * @created 19/mar/2009
 */
require_once("DBEntity.php");

class Event extends DBEntity
{
	const TABLE = 'gallery_events';
	const PRIMARY_KEY = 'event_id';
	const DATE_FORMAT ="j/m/Y";
	
	public function __construct(DB $db_wrapper, $id=null)
	{
		parent::__construct($db_wrapper, self::TABLE, self::PRIMARY_KEY, $id);
	}
	
	public static function getFromId(DB $db_wrapper, $event_id)
	{
		return parent::getFromId($db_wrapper, self::TABLE, self::PRIMARY_KEY, $event_id);
	}
	
	public static function getJSONFromId(DB $db_wrapper, $event_id)
	{
		return parent::getJSONFromId($db_wrapper, self::TABLE, self::PRIMARY_KEY, $event_id);
	}
	
	/**
	 * Restituisce il json degli eventi appartenenti all'utente
	 * 
	 * @param DB $db_wrapper il wrapper del DB
	 * @param $user_id l'id del'utente, se il valore e' null, allora nel json saranno inseriti
	 * 				tutti gli eventi presenti nel database senza distinzione di utente
	 * @param $showHidden se true inserisce anche gli eventi nascosti altrimenti gli esclude
	 * @param $from 
	 * @param $to
	 */
	public static function getJSONArrayFromUserId(DB $db_wrapper, $user_id=null, $showHidden=0, $from=null, $to=null)
	{
		$table = self::TABLE;
		$pk = self::PRIMARY_KEY;
		
		$JSON = "{\n";
		
		$bio = null;
		if(!is_null($user_id))
		{
			$user = User::getFromId($db_wrapper, $user_id);
			$bio = $user->get('user_description');
			$JSON .= "\t\"bio\": \"$bio\" ,\n";
		}
		
		$JSON .= "\t\"items\": [\n\t";
		
		$mysql_query = "SELECT * " .
				"FROM $table ";

		if(!is_null($user_id)) 
		{
			$mysql_query .= "WHERE user_id=$user_id ";
			if(!is_null($from)) 
				$mysql_query .= "AND event_start >= $from ";
			if(!is_null($to)) 
				$mysql_query .= "AND event_end < $to ";
			if(!$showHidden)
				$mysql_query .= "AND event_hidden=0 ";	
		}
		else
		{
			if(!is_null($from)) 
			{
				$mysql_query .= "WHERE event_start >= $from ";
				if(!is_null($to)) 
					$mysql_query .= "AND event_end < $to ";	
				if(!$showHidden && is_null($user_id))
					$mysql_query .= "AND event_hidden=0 ";
			}
			else
			{
				if(!is_null($to)) 
					$mysql_query .= "WHERE event_end < $to ";	
			}
		}		
		
		//echo $mysql_query ."<br />\n";
		$result = $db_wrapper->query($mysql_query);
		
		// itero su ogni evento
		$j = 1;
		while($row = mysql_fetch_assoc($result))
		{
			$JSON .= "{\n";
			
			// itero su ogni elemento dell'evento
			$i = 0;
			foreach($row as $key => $value)
			{
				if(strcmp($key, 'event_start')==0 || strcmp($key, 'event_end')==0)
					$value = date(self::DATE_FORMAT, $value);
				$JSON .= "\t\t\"".$key."\":\"".$value."\"";
				if($i < count($row)-1)
					$JSON .= " ,\n";
				else
					$JSON .= "\n";
					
				$i++;
			}
			$JSON .= "\t}";
			
			if($j < mysql_num_rows($result))
				$JSON .= " , ";
			$j++;
		}
		$JSON .= "\n\t]\n" .
				"}";
		return $JSON;
	}
}
?>
